#! /usr/bin/env	python

# this script used to change wiggle file into bed file


def wiggle2bed(wigfile,outfile):
	f = open(wigfile,'r')
	f2 = open(outfile,'w')
	sepstring = 'fixedStep'
	ALL = f.read()
	ALL = ALL.split(sepstring)[1:]
	for all in ALL: 
		desline = all.split(os.linesep,1)[0]
		chr = desline.split()[0].split('=')[1]
		start = int(desline.split()[1].split('=')[1])
		step = int(desline.split()[2].split('=')[1])
		end = (all.count(os.linesep)-2)*step+start
		print >>f2, '\t'.join([chr,repr(start),repr(end)]) # ,'\t',start,'\t',end
	f.close()
	f2.close()
	
if __name__ == '__main__': 
	import sys
	import time
	import os
	
	if len(sys.argv) == 1:
		print "usage:python wib2bed.py wigfile bedfile"
		print "the output filename is: [wigfile].bed in the current folder"
	else:
		wigfile = sys.argv[1]
		outfile = sys.argv[2]
		starttime = time.time()
		wiggle2bed(wigfile,outfile)
		endtime = time.time()
		print "DONE! Takes %f seconds" % (endtime-starttime)
		 
